package com.tom.jmgd.config;

import com.alibaba.fastjson.JSONObject;
import com.tom.jmgd.util.HttpUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.UUID;

public class WechatConfig {

    // 微信公众号的Token
//    private static final String TOKEN = "YOUR_TOKEN";

    // 生成随机字符串
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    // 生成当前时间的时间戳（秒）
    public static String generateTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    // SHA1加密
    private static String sha1(String input) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        byte[] result = digest.digest(input.getBytes());
        Formatter formatter = new Formatter();
        for (byte b : result) {
            formatter.format("%02x", b);
        }
        String hash = formatter.toString();
        formatter.close();
        return hash;
    }

    // 根据参数生成签名
    public static String generateSignature(String jsapiTicket, String nonceStr, String timestamp, String url) throws NoSuchAlgorithmException {
        String[] arr = new String[]{"jsapi_ticket=" + jsapiTicket, "noncestr=" + nonceStr, "timestamp=" + timestamp, "url=" + url};
        Arrays.sort(arr);
        String str = String.join("&", arr);
        return sha1(str);
    }

    public static void main(String[] args) throws Exception {
        String nonceStr = generateNonceStr();
        String timestamp = generateTimestamp();
        String url = "http://cj.jmgdyf.com/"; // 需要动态获取当前页面的URL
        String result = HttpUtil.getRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx31bbd830784df0f3&secret=210654aa4ec27bc390efead48bac928e");
        //System.out.println(JSONObject.parseObject(result).getString("access_token"));
        String result2 = HttpUtil.getRequest("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+JSONObject.parseObject(result).getString("access_token")+"&type=jsapi");
        //System.out.println(JSONObject.parseObject(result2).getString("ticket"));
        String jsapiTicket = JSONObject.parseObject(result2).getString("ticket"); // 从服务器获取微信JS-SDK的票据

        String signature = generateSignature(jsapiTicket, nonceStr, timestamp, url);

        System.out.println("NonceStr: " + nonceStr);
        System.out.println("Timestamp: " + timestamp);
        System.out.println("jsapiTicket: " + jsapiTicket);
        System.out.println("url: " + url);
        System.out.println("Signature: " + signature);
    }
}

